#include <iostream>
#include <string>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
class Sem{
    public:
    Sem(int num){
        //初始化
        sem_init(&_sem,0,num);
    }
    ~Sem(){
        sem_destroy(&_sem);
    }
    void P(){
        //等待信号量-1
        sem_wait(&_sem);
    }
    void V(){
        //释放信号量+1
        sem_post(&_sem);
    }
    private:
    sem_t _sem;
};
int tickets = 1000;
Sem sem(1);
void* TicketGet(void* arg){
    //里面要进行抢票逻辑，arg是我们线程的名字
    std::string name = (char*)arg;
    while(1){
        sem.P();
        if(tickets > 0){
            usleep(1000);
            std::cout<<name<<"ticket left:"<<--tickets<<std::endl;
            sem.V(); 
        }
        else{
            sem.V();
            break;
        }
    }
    std::cout<<name<<" quit"<<std::endl;
    return (void*)2025;
}

int main(){
    pthread_t tid1,tid2,tid3,tid4;
    pthread_create(&tid1,nullptr,TicketGet,(void*)"thread 1");
    pthread_create(&tid2,nullptr,TicketGet,(void*)"thread 2");
    pthread_create(&tid3,nullptr,TicketGet,(void*)"thread 3");
    pthread_create(&tid4,nullptr,TicketGet,(void*)"thread 4");

    pthread_join(tid1,nullptr);
    pthread_join(tid2,nullptr);
    pthread_join(tid3,nullptr);
    pthread_join(tid4,nullptr);
    return 0;
}